package com.springboot.scheduled;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by weiyonghua on 2017/7/16.
 */
@Component
public class ScheduledTasks {
    private static final Logger log = LoggerFactory.getLogger(ScheduledTasks.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    /**
     * 上一次开始执行时间点之后5秒再执行
     */
    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime1() {
        log.info("[reportCurrentTime1]The time is now {}", dateFormat.format(new Date()));
    }

    /**
     * 上一次执行完毕时间点之后5秒再执行
     */
    @Scheduled(fixedDelay  = 5000)
    public void reportCurrentTime2() {
        log.info("[reportCurrentTime2]The time is now {}", dateFormat.format(new Date()));
    }

    /**
     * 第一次延迟1秒后执行，之后按fixedRate的规则每5秒执行一次
     */
    @Scheduled(initialDelay=1000, fixedRate=5000)
    public void reportCurrentTime3() {
        log.info("[reportCurrentTime3]The time is now {}", dateFormat.format(new Date()));
    }

    /**
     * 通过cron表达式定义规则
     */
    @Scheduled(cron="*/5 * * * * ?")
    public void reportCurrentTime4() {
        log.info("[reportCurrentTime4]The time is now {}", dateFormat.format(new Date()));
    }
}
